package jnpf.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.exception.DataException;
import jnpf.permission.entity.UserEntity;
import jnpf.service.*;
import jnpf.entity.*;
import jnpf.util.*;
import jnpf.model.tagmange.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.*;
import jnpf.annotation.JnpfField;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.base.vo.DownloadVO;
import jnpf.config.ConfigValueUtil;
import jnpf.base.entity.ProvinceEntity;
import java.io.IOException;
import java.util.stream.Collectors;
import jnpf.engine.entity.FlowTaskEntity;
import jnpf.exception.WorkFlowException;
import org.springframework.web.multipart.MultipartFile;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.File;
import jnpf.onlinedev.model.ExcelImFieldModel;
import jnpf.onlinedev.model.OnlineImport.ImportDataModel;
import jnpf.onlinedev.model.OnlineImport.ImportFormCheckUniqueModel;
import jnpf.onlinedev.model.OnlineImport.ExcelImportModel;
import jnpf.onlinedev.model.OnlineImport.VisualImportModel;
import cn.xuyanwu.spring.file.storage.FileInfo;
import lombok.Cleanup;
import jnpf.model.visualJson.config.HeaderModel;
import jnpf.base.model.ColumnDataModel;
import jnpf.base.util.VisualUtils;
import org.springframework.transaction.annotation.Transactional;

/**
 * tagMange
 * @版本： V3.5
 * @版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * @作者： JNPF开发平台组
 * @日期： 2025-04-12
 */
@Slf4j
@RestController
@Tag(name = "tagMange" , description = "example")
@RequestMapping("/api/example/TagMange")
public class TagMangeController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private TagMangeService tagMangeService;



    @Autowired
    private ConfigValueUtil configValueUtil;

    /**
    * 列表
    *
    * @param tagMangePagination
    * @return
    */
    @Operation(summary = "获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody TagMangePagination tagMangePagination)throws IOException{
        List<TagMangeEntity> list= tagMangeService.getList(tagMangePagination);
        List<Map<String, Object>> realList=new ArrayList<>();
        for (TagMangeEntity entity : list) {
        Map<String, Object> tagMangeMap=JsonUtil.entityToMap(entity);
        tagMangeMap.put("id", tagMangeMap.get("id"));
        //副表数据
        //子表数据
            realList.add(tagMangeMap);
        }
        //数据转换
        realList = generaterSwapUtil.swapDataList(realList, TagMangeConstant.getFormData(), TagMangeConstant.getColumnData(), tagMangePagination.getModuleId(),false);

        //返回对象
        PageListVO vo = new PageListVO();
        vo.setList(realList);
        PaginationVO page = JsonUtil.getJsonToBean(tagMangePagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);
    }
    /**
    * 创建
    *
    * @param tagMangeForm
    * @return
    */
    @PostMapping()
    @Operation(summary = "创建")
    public ActionResult create(@RequestBody @Valid TagMangeForm tagMangeForm) {
        String b = tagMangeService.checkForm(tagMangeForm,0);
        if (StringUtil.isNotEmpty(b)){
            return ActionResult.fail(b );
        }
        try{
            tagMangeService.saveOrUpdate(tagMangeForm, null ,true);
        }catch(Exception e){
            return ActionResult.fail("新增数据失败");
        }
        return ActionResult.success("创建成功");
    }
    /**
    * 导出Excel
    *
    * @return
    */
    @Operation(summary = "导出Excel")
    @PostMapping("/Actions/Export")
    public ActionResult Export(@RequestBody TagMangePagination tagMangePagination) throws IOException {
        if (StringUtil.isEmpty(tagMangePagination.getSelectKey())){
            return ActionResult.fail("请选择导出字段");
        }
        List<TagMangeEntity> list= tagMangeService.getList(tagMangePagination);
        List<Map<String, Object>> realList=new ArrayList<>();
        for (TagMangeEntity entity : list) {
        Map<String, Object> tagMangeMap=JsonUtil.entityToMap(entity);
        tagMangeMap.put("id", tagMangeMap.get("id"));
        //副表数据
        //子表数据
            realList.add(tagMangeMap);
        }
        //数据转换
        realList = generaterSwapUtil.swapDataList(realList, TagMangeConstant.getFormData(), TagMangeConstant.getColumnData(), tagMangePagination.getModuleId(),false);
        String[]keys=!StringUtil.isEmpty(tagMangePagination.getSelectKey())?tagMangePagination.getSelectKey():new String[0];
        UserInfo userInfo=userProvider.get();
            DownloadVO vo=this.creatModelExcel(configValueUtil.getTemporaryFilePath(),realList,keys,userInfo);
        return ActionResult.success(vo);
    }

    /**
    * 导出表格方法
    */
    public DownloadVO creatModelExcel(String path,List<Map<String, Object>>list,String[]keys,UserInfo userInfo){
        DownloadVO vo=DownloadVO.builder().build();
        List<ExcelExportEntity> entitys=new ArrayList<>();
        if(keys.length>0){
            for(String key:keys){
                switch(key){
                    case "tagId" :
                    entitys.add(new ExcelExportEntity("标签名称" ,"tagId"));
                    break;
                    case "tagType" :
                    entitys.add(new ExcelExportEntity("绑定类型" ,"tagType"));
                    break;
                    case "templateId" :
                    entitys.add(new ExcelExportEntity("模板名称" ,"templateId"));
                    break;
                    case "themeId" :
                    entitys.add(new ExcelExportEntity("主题名称" ,"themeId"));
                    break;
                    case "entityId" :
                    entitys.add(new ExcelExportEntity("实体名称" ,"entityId"));
                    break;
                    case "enabled" :
                    entitys.add(new ExcelExportEntity("是否启用" ,"enabled"));
                    break;
                    case "createUserId" :
                    entitys.add(new ExcelExportEntity("创建用户id" ,"createUserId"));
                    break;
                    case "createTime" :
                    entitys.add(new ExcelExportEntity("创建时间" ,"createTime"));
                    break;
                    default:
                    break;
                }
            }
        }

        ExportParams exportParams = new ExportParams(null, "表单信息");
        exportParams.setType(ExcelType.XSSF);
        try{
            @Cleanup Workbook workbook = new HSSFWorkbook();
            if (entitys.size()>0){
                if (list.size()==0){
                    list.add(new HashMap<>());
                }
                //去除空数据
                List<Map<String, Object>> dataList = new ArrayList<>();
                for (Map<String, Object> map : list) {
                    int i = 0;
                    for (String key : keys) {
                        //子表
                        if (key.toLowerCase().startsWith("tablefield")) {
                            String tableField = key.substring(0, key.indexOf("-" ));
                            String field = key.substring(key.indexOf("-" ) + 1);
                            Object o = map.get(tableField);
                            if (o != null) {
                                List<Map<String, Object>> childList = (List<Map<String, Object>>) o;
                                for (Map<String, Object> childMap : childList) {
                                    if (childMap.get(field) != null) {
                                        i++;
                                    }
                                }
                            }
                        } else {
                            Object o = map.get(key);
                            if (o != null) {
                                i++;
                            }
                        }
                    }
                    if (i > 0) {
                        dataList.add(map);
                    }
                }
                //复杂表头-表头和数据处理
                ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(TagMangeConstant.getColumnData(), ColumnDataModel.class);
                List<HeaderModel> complexHeaderList = columnDataModel.getComplexHeaderList();
                if (!Objects.equals(columnDataModel.getType(), 3) && !Objects.equals(columnDataModel.getType(), 5)) {
                    entitys = VisualUtils.complexHeaderHandel(entitys, complexHeaderList);
                    dataList =  VisualUtils.complexHeaderDataHandel(dataList, complexHeaderList);
                }

                workbook = ExcelExportUtil.exportExcel(exportParams, entitys, dataList);
            }
            String fileName = "表单信息" + DateUtil.dateNow("yyyyMMdd") + "_" + RandomUtil.uuId() + ".xlsx";
            MultipartFile multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook, fileName);
            String temporaryFilePath = configValueUtil.getTemporaryFilePath();
            FileInfo fileInfo = FileUploadUtils.uploadFile(multipartFile, temporaryFilePath, fileName);
            vo.setName(fileInfo.getFilename());
            vo.setUrl(UploaderUtil.uploaderFile(fileInfo.getFilename() + "#" + "Temporary") + "&name=" + fileName);
        } catch (Exception e) {
            log.error("信息导出Excel错误:{}", e.getMessage());
            e.printStackTrace();
        }
        return vo;
    }
    /**
    * 批量删除
    * @param ids
    * @return
    */
    @DeleteMapping("/batchRemove")
    @Transactional
    @Operation(summary = "批量删除")
    public ActionResult batchRemove(@RequestBody String ids){
        List<String> idList = JsonUtil.getJsonToList(ids, String.class);
        int i =0;
        for (String allId : idList){
            this.delete(allId);
            i++;
        }
        if (i == 0 ){
        return ActionResult.fail("删除失败");
        }
        return ActionResult.success("删除成功");
    }
    /**
    * 编辑
    * @param id
    * @param tagMangeForm
    * @return
    */
    @PutMapping("/{id}")
    @Operation(summary = "更新")
    public ActionResult update(@PathVariable("id") String id,@RequestBody @Valid TagMangeForm tagMangeForm,
                                @RequestParam(value = "isImport", required = false) boolean isImport){
        tagMangeForm.setId(id);
        if (!isImport) {
            String b =  tagMangeService.checkForm(tagMangeForm,1);
            if (StringUtil.isNotEmpty(b)){
                return ActionResult.fail(b );
            }
        }
        TagMangeEntity entity= tagMangeService.getInfo(id);
        if(entity!=null){
            try{
                tagMangeService.saveOrUpdate(tagMangeForm,id,false);
            }catch(Exception e){
                return ActionResult.fail("修改数据失败");
            }
            return ActionResult.success("更新成功");
        }else{
            return ActionResult.fail("更新失败，数据不存在");
        }
    }
    /**
    * 删除
    * @param id
    * @return
    */
    @Operation(summary = "删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id){
        TagMangeEntity entity= tagMangeService.getInfo(id);
        if(entity!=null){
            //主表数据删除
            tagMangeService.delete(entity);
        }
        return ActionResult.success("删除成功");
    }
    /**
    * 表单信息(详情页)
    * 详情页面使用-转换数据
    * @param id
    * @return
    */
    @Operation(summary = "表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult detailInfo(@PathVariable("id") String id){
        TagMangeEntity entity= tagMangeService.getInfo(id);
        if(entity==null){
            return ActionResult.fail("表单数据不存在！");
        }
        Map<String, Object> tagMangeMap=JsonUtil.entityToMap(entity);
        tagMangeMap.put("id", tagMangeMap.get("id"));
        //副表数据
        //子表数据
        tagMangeMap = generaterSwapUtil.swapDataDetail(tagMangeMap,TagMangeConstant.getFormData(),"680792260320699525",false);
        return ActionResult.success(tagMangeMap);
    }
    /**
    * 获取详情(编辑页)
    * 编辑页面使用-不转换数据
    * @param id
    * @return
    */
    @Operation(summary = "信息")
    @GetMapping("/{id}")
    public ActionResult info(@PathVariable("id") String id){
        TagMangeEntity entity= tagMangeService.getInfo(id);
        if(entity==null){
            return ActionResult.fail("表单数据不存在！");
        }
        Map<String, Object> tagMangeMap=JsonUtil.entityToMap(entity);
        tagMangeMap.put("id", tagMangeMap.get("id"));
        //副表数据
        //子表数据
        tagMangeMap = generaterSwapUtil.swapDataForm(tagMangeMap,TagMangeConstant.getFormData(),TagMangeConstant.TABLEFIELDKEY,TagMangeConstant.TABLERENAMES);
        return ActionResult.success(tagMangeMap);
    }

}
